#include "i2c_comu.h"
#include "gd32f4xx_rcu.h"               // GigaDevice::Device:StdPeripherals:RCU


void I2C_Init(uint32_t I2Cx)
{
	I2C_RCU_Init(I2Cx);
	I2C_gpio_Init(I2Cx);
	I2C_GPIO_Configuration(I2Cx);
}

void I2C_RCU_Init(uint32_t I2Cx)
{
	switch(I2Cx)
	{
		case I2C0:
			break;
		case I2C1:
			break;
		case I2C2:
				i2c_deinit(I2C2);
				rcu_periph_clock_enable(RCU_GPIOA);
				rcu_periph_clock_enable(RCU_GPIOC);
				rcu_periph_clock_enable(RCU_I2C2);
			break;
		default:
			break;
	}
}

void I2C_gpio_Init(uint32_t I2Cx)
{
	uint32_t sclPort=0,sclPin=0;
	uint32_t sdaPort=0,sdaPin=0;
	uint32_t sclAF=0, sdaAF=0;
	switch(I2Cx)
	{
		case I2C0:
			break;
		case I2C1:
			break;
		case I2C2:
			sclPort=GPIOA;
			sclPin=GPIO_PIN_8;
			sclAF=GPIO_AF_4;
			sdaPort=GPIOC;
			sdaPin=GPIO_PIN_9;
			sdaAF=GPIO_AF_4;
			break;
		
		default:
			return;
	}
	
	
	gpio_mode_set(sclPort, GPIO_MODE_AF, GPIO_PUPD_PULLUP, sclPin);
	gpio_output_options_set(sclPort, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ, sclPin);
	gpio_mode_set(sdaPort, GPIO_MODE_AF, GPIO_PUPD_PULLUP, sdaPin);
	gpio_output_options_set(sdaPort, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ, sdaPin);
	
	gpio_af_set(sclPort, sclAF, sclPin);
	gpio_af_set(sdaPort, sdaAF, sdaPin);
}


void I2C_GPIO_Configuration(uint32_t I2Cx)
{
	switch(I2Cx)
	{
		case I2C0:
			break;
		case I2C1:
			break;
		case I2C2:
				i2c_clock_config(I2Cx, 400000, I2C_DTCY_2);
				i2c_mode_addr_config(I2Cx,I2C_I2CMODE_ENABLE,I2C_ADDFORMAT_7BITS, I2C2_SLAVE_ADDRESS7);
				i2c_enable(I2C2);
			break;
		default:
			break;
	}

}

/**
** 主机模式下，接收2个字节的数据
**
**/
int8_t I2C_Master_Recv_Word(uint32_t I2Cx,uint8_t address7, uint8_t* recvBuffer)
{
	i2c_ack_config(I2Cx,I2C_ACK_DISABLE);
	i2c_ackpos_config(I2Cx,I2C_ACK_ENABLE);	//在下一个字节传完后，送上master ack
	//将Start置为1
	i2c_start_on_bus(I2Cx);
	while(SET!=i2c_flag_get(I2Cx,I2C_SBSEND))
	{
	}
	//进入主机模式
	//写入要接收从设备的地址
	i2c_master_addressing(I2Cx, address7, I2C_RECEIVER);
		
	while(SET!=i2c_flag_get(I2Cx, I2C_ADDSEND))
	{
		
	}
		i2c_ack_config(I2Cx,I2C_ACK_ENABLE);

	//清除 Address Sent 标志位
	i2c_flag_clear(I2Cx, I2C_STAT0_ADDSEND);
	
	while(SET!=i2c_flag_get(I2Cx, I2C_BTC))
	{
		
	}

	i2c_stop_on_bus(I2Cx);
	
	recvBuffer[0]=i2c_receive_data(I2Cx);
	recvBuffer[1]=i2c_receive_data(I2Cx);
	i2c_flag_clear(I2Cx, I2C_BTC);
	//i2c_flag_clear(I2Cx, I2C_STAT0_RBNE);

	//i2c_stop_on_bus(I2Cx);
	
	return 0;
}
